import {
  Controller,
  Post,
  Provide,
  Put,
  Get,
  Body,
  Inject,
  Param,
  Del,
  Query,
} from '@midwayjs/core';
import { UserDTO } from '../dto/user';
import { UserService } from '../service/user';
import { RuleType, Valid } from '@midwayjs/validate';
import { R } from '../../../common/base.error.util';
import { FindOptionsWhere, Like } from 'typeorm';
import { UserEntity } from '../entity/user';

@Provide()
@Controller('/user', { description: '用户管理' })
export class UserController {
  @Inject()
  userService: UserService;
  @Post('/', { description: '创建' })
  async create(@Body() data: UserDTO) {
    return await this.userService.createUser(data);
  }

  @Put('/', { description: '编辑' })
  async edit(@Body() data: UserDTO) {
    return await this.userService.editUser(data);
  }

  @Del('/:id', { description: '删除' })
  async remove(
    @Valid(RuleType.number().required().error(R.error('id不能为空')))
    @Param('id')
    id: number
  ) {
    await this.userService.removeUser(id);
  }

  @Get('/:id', { description: '根据id查询' })
  async getById(@Param('id') id: string) {
    return await this.userService.getById(id);
  }
  
  @Get('/page', { description: '分页查询' })
  async page(
    @Query('page') page: number,
    @Query('size') size: number,
    @Query('nickName') nickName: string,
    @Query('phone') phone: string
  ) {
    const query: FindOptionsWhere<UserEntity> = {};
    if (phone) {
      query.phone = Like(`%${phone}%`);
    }
    if (nickName) {
      query.nickName = Like(`%${nickName}%`);
    }
    return await this.userService.page(page, size, query);
  }
}
